package net.wofly.right.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Desc:
 * Created by LiuJianbo on 2017/11/6.
 */
public class MyModularRealm extends ModularRealmAuthenticator {

    @Override
    protected void assertRealmsConfigured() throws IllegalStateException {
        super.assertRealmsConfigured();
    }

    @Override
    protected AuthenticationInfo doSingleRealmAuthentication(
            Realm realm, AuthenticationToken token) {
        return super.doSingleRealmAuthentication(realm, token);
    }

    @Override
    protected AuthenticationInfo doMultiRealmAuthentication(
            Collection<Realm> realms, AuthenticationToken token) {
        return super.doMultiRealmAuthentication(realms, token);
    }

    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        // 判断getRealms()是否返回为空
        assertRealmsConfigured();
        // 强制转换回自定义的CustomizedToken
        MyUsernamePasswordToken usernamePasswordToken = (MyUsernamePasswordToken) authenticationToken;
        // 登录类型
        LoginType loginType = usernamePasswordToken.getLoginType();
        // 所有Realm
        Collection<Realm> realms = getRealms();
        // 登录类型对应的所有Realm
        Collection<Realm> typeRealms = new ArrayList<Realm>();
        for (Realm realm : realms) {
            if (realm.getName().contains(loginType.name())) {
                typeRealms.add(realm);
            }
        }

        // 判断是单Realm还是多Realm
        if (typeRealms.size() == 1) {
            return doSingleRealmAuthentication(typeRealms.iterator().next(), usernamePasswordToken);
        } else {
            return doMultiRealmAuthentication(typeRealms, usernamePasswordToken);
        }
    }


}
